document.addEventListener('DOMContentLoaded', function () {
    const navLinks = document.querySelectorAll('.nav-link');
    const contentAreas = document.querySelectorAll('.content');

    // 模拟点击第一个带有 active 类的导航链接
    const activeLink = document.querySelector('.nav-link.active');
    if (activeLink) {
        const targetId = activeLink.dataset.target;
        const targetContent = document.getElementById(targetId);
        navLinks.forEach(navLink => navLink.classList.remove('active'));
        contentAreas.forEach(content => content.classList.remove('active'));
        activeLink.classList.add('active');
        if (targetContent) {
            targetContent.classList.add('active');
        }
    }

    navLinks.forEach(link => {
        link.addEventListener('click', function (e) {
            navLinks.forEach(navLink => navLink.classList.remove('active'));
            contentAreas.forEach(content => content.classList.remove('active'));
            this.classList.add('active');
            const targetId = this.dataset.target;
            const targetContent = document.getElementById(targetId);
            if (targetContent) {
                targetContent.classList.add('active');
            }
        });
    });
    const tables = document.querySelectorAll('.adminManagement-table');
    tables.forEach(function (table) {
        const selectAll = table.querySelector('.selectAll');
        const rowCheckboxes = table.querySelectorAll('.rowCheckbox');

        selectAll.addEventListener('change', function () {
            const isChecked = this.checked;
            rowCheckboxes.forEach(function (checkbox) {
                checkbox.checked = isChecked;
            });
        });

        rowCheckboxes.forEach(function (checkbox) {
            checkbox.addEventListener('change', function () {
                const allChecked = Array.from(rowCheckboxes).every(function (cb) {
                    return cb.checked;
                });
                selectAll.checked = allChecked;
            });
        });
    });
//分页
    $(document).ready(function () {
        const rowsPerPage = 10; // 每页显示的行数
        const $tableBody = $('#postList');
        const rows = $tableBody.find('tr');
        const numPages = Math.ceil(rows.length / rowsPerPage);

        function showPage(pageNumber) {
            const startIndex = (pageNumber - 1) * rowsPerPage;
            const endIndex = startIndex + rowsPerPage;
            rows.hide().slice(startIndex, endIndex).show();

            const $pageNav = $('#pageNav');
            $pageNav.empty();

            for (let i = 1; i <= numPages; i++) {
                const $a = $('<a href="#">').text(i);
                if (i === pageNumber) {
                    $a.addClass('active');
                }
                $a.click(function (e) {
                    e.preventDefault();
                    showPage(i);
                });
                $pageNav.append($a);
            }
        }

        showPage(1);
    });
    $(document).ready(function () {
        const rowsPerPage = 3; // 每页显示的行数
        const $tableBody = $('#postList');
        const rows = $tableBody.find('tr');
        const numPages = Math.max(1, Math.ceil(rows.length / rowsPerPage)); // 至少有一页
        let currentPage = 1;

        // 显示指定页的数据
        function showPage(pageNumber) {
            currentPage = pageNumber;
            const startIndex = (pageNumber - 1) * rowsPerPage;
            const endIndex = startIndex + rowsPerPage;

            // 隐藏所有行，然后显示当前页的行
            rows.hide();
            rows.slice(startIndex, endIndex).show();

            // 更新分页导航
            updatePagination();
        }

        // 更新分页导航
        function updatePagination() {
            const $pageNav = $('#pageNav');
            $pageNav.empty();

            // 添加"上一页"按钮
            const $prevBtn = $('<a href="#" class="prev-btn">').text('上一页');
            if (currentPage === 1) {
            } else {
                $prevBtn.click(function (e) {
                    e.preventDefault();
                    showPage(currentPage - 1);
                });
            }
            $pageNav.append($prevBtn);

            // 添加页码按钮
            // 只显示当前页附近的页码，避免过多按钮
            const maxVisiblePages = 5;
            let startPage = Math.max(1, currentPage - Math.floor(maxVisiblePages / 2));
            let endPage = startPage + maxVisiblePages - 1;

            if (endPage > numPages) {
                endPage = numPages;
                startPage = Math.max(1, endPage - maxVisiblePages + 1);
            }

            // 添加省略号（如果需要）
            if (startPage > 1) {
                $pageNav.append($('<span>').text('...'));
            }

            for (let i = startPage; i <= endPage; i++) {
                const $pageBtn = $('<a href="#" class="num">').text(i);
                if (i === currentPage) {
                    $pageBtn.addClass('active');
                } else {
                    $pageBtn.click(function (e) {
                        e.preventDefault();
                        showPage(i);
                    });
                }
                $pageNav.append($pageBtn);
            }

            // 添加省略号（如果需要）
            if (endPage < numPages) {
                $pageNav.append($('<span>').text('...'));
            }

            // 添加"下一页"按钮
            const $nextBtn = $('<a href="#" class="next-btn">').text('下一页');
            if (currentPage === numPages) {
                $nextBtn.addClass('disabled');
            } else {
                $nextBtn.click(function (e) {
                    e.preventDefault();
                    showPage(currentPage + 1);
                });
            }
            $pageNav.append($nextBtn);
        }

        // 初始化页面
        if (rows.length > 0) {
            showPage(1);
        }
    });
    //帖子编辑

    const namePostTitle = document.getElementById('namePostTitle');
    const editButtons = document.querySelectorAll('.editbtn');

    const reportButtons = document.querySelectorAll('.reportedit');

    const editPostTitleInput = document.getElementById('editPostTitle');
    const editPostContentDiv = document.getElementById('editPostContentDivs');
    let currentEditRow;
    // 封装打开模态框并填充数据的函数
    function openModalAndFillData(modalId, button) {
        const modal = document.getElementById(modalId);
        modal.style.display = 'block';
        const currentRow = button.closest('tr');
        return currentRow;
    }
    //驳回和通过
    // 通过按钮
    document.querySelectorAll('.editbtns.text-xl:last-child').forEach(button => {
        button.addEventListener('click', function() {
            const postId = this.getAttribute('data-id');
            handlePostAction(postId, '通过', '/admin/toApprovePost');
        });
    });

    // 驳回按钮
    document.querySelectorAll('.deletebtn').forEach(button => {
        button.addEventListener('click', function() {
            const postId = this.getAttribute('data-id');
            handlePostAction(postId, '驳回', '/admin/toRejectPost');
        });
    });

    function handlePostAction(postId, actionText, apiUrl) {
        if (confirm(`确定要${actionText}这个帖子吗？`)) {
            $.ajax({
                url: `${apiUrl}?id=${postId}`,
                type: 'GET',
                success: function (response) {
                    alert(`${actionText}成功`);
                    location.reload();
                },
                error: function (error) {
                    console.error(`${actionText}失败`, error);
                    alert(`${actionText}失败，请稍后再试`);
                }
            });
        }
    }

    // 点击编辑按钮，打开弹窗并填充数据
    editButtons.forEach(function (editButton) {
        editButton.addEventListener('click', function () {
            currentEditRow = openModalAndFillData('editModal', this);
            const name = currentEditRow.querySelector('td:nth-child(2)').textContent;
            const title = currentEditRow.querySelector('td:nth-child(3)').textContent;
            const fullContentCell = currentEditRow.querySelector('td:nth-child(5)');
            let fullContent = fullContentCell.innerHTML;

            // 去除 .contents 类
            const tempDiv = document.createElement('div');
            tempDiv.innerHTML = fullContent;
            const contentsDiv = tempDiv.querySelector('.contents');
            if (contentsDiv) {
                contentsDiv.classList.remove('contents');
            }
            fullContent = tempDiv.innerHTML;

            // 填充姓名到输入框
            namePostTitle.value = name;
            editPostTitleInput.value = title;
            editPostContentDiv.innerHTML = fullContent;
        });
    });


    reportButtons.forEach(function (reportButton) {
        reportButton.addEventListener('click', function () {
            currentEditRow = openModalAndFillData('reportEditModal', this);
            const name = currentEditRow.querySelector('td:nth-child(2)').textContent;
            const reportContent = currentEditRow.querySelector('td:nth-child(3)').textContent;
            const reporter = currentEditRow.querySelector('td:nth-child(5)').textContent;

            const reportNamePostTitle = document.getElementById('reportNamePostTitle');
            const reportEditPostTitle = document.getElementById('reportEditPostTitle');
            const reportEditPostContentDiv = document.getElementById('reportEditPostContentDivs');

            reportNamePostTitle.value = name;
            reportEditPostTitle.value = reporter;
            reportEditPostContentDiv.innerHTML = reportContent;

            const reportEditModal = document.getElementById('reportEditModal');
            reportEditModal.style.display = 'block';
        });
    });


    const editModalSaveButton = document.getElementById('editModalSaveButton');
    editModalSaveButton.addEventListener('click', function () {
        const newName = document.getElementById('namePostTitle').value;
        const newTitle = document.getElementById('editPostTitle').value;
        const newContent = document.getElementById('editPostContentDivs').innerHTML;

        if (currentEditRow) {
            const nameCell = currentEditRow.querySelector('td:nth-child(2)');
            if (nameCell) {
                nameCell.textContent = newName;
            }

            const titleCell = currentEditRow.querySelector('td:nth-child(3)');
            if (titleCell) {
                titleCell.textContent = newTitle;
            }

            const contentCell = currentEditRow.querySelector('td:nth-child(5)');
            if (contentCell) {
                // 重新添加.contents类
                const tempDiv = document.createElement('div');
                tempDiv.innerHTML = newContent;
                const contentDiv = tempDiv.querySelector('div');
                if (contentDiv) {
                    contentDiv.classList.add('contents');
                }
                contentCell.innerHTML = tempDiv.innerHTML;
            }
        }
        document.getElementById('editModal').style.display = 'none';
    });



    const modals = ['editModal', 'userEditModal', 'commentEditModal', 'categoryEditModal', 'reportEditModal'];
    modals.forEach(function (modalId) {
        const modal = document.getElementById(modalId);
        if (modal) {
            modal.style.display = 'none';
        }
    });
});

// 为所有取消按钮添加点击事件
const cancelEditPostButtons = document.querySelectorAll('.cancelEditPost');
cancelEditPostButtons.forEach(function (cancelEditPostButton) {
    cancelEditPostButton.addEventListener('click', function () {
        const modals = ['editModal', 'userEditModal', 'commentEditModal', 'categoryEditModal', 'reportEditModal'];
        modals.forEach(function (modalId) {
            const modal = document.getElementById(modalId);
            if (modal) {
                modal.style.display = 'none';
            }
        });
    });
    //添加

    // 获取DOM元素
    const addButton1 = document.getElementById('addButton1');
    const addModal = document.getElementById('addModal');
    const saveButton = document.querySelector('.saveEditPost');
    const cancelButton = document.querySelector('.cancelEditPost0');
    const nameInput = document.getElementById('namePostTitle1');
    const titleInput = document.getElementById('editPostTitle1');
    const contentDiv = document.getElementById('editPostContentDiv');

// 打开模态框
    addButton1.addEventListener('click', function() {
        addModal.style.display = 'block';
        // 清空之前的输入
        nameInput.value = '';
        titleInput.value = '';
        contentDiv.textContent = '';
    });

// 关闭模态框
    cancelButton.addEventListener('click', function() {
        addModal.style.display = 'none';
    });

// 点击模态框外部关闭
    window.addEventListener('click', function(event) {
        if (event.target === addModal) {
            addModal.style.display = 'none';
        }
    });

// 保存按钮点击事件 - 使用 jQuery AJAX
    saveButton.addEventListener('click', function() {
        // 表单验证
        if (!validateForm()) {
            return;
        }

        // 收集表单数据
        const formData = {
            nickname: nameInput.value.trim(),
            title: titleInput.value.trim(),
            content: contentDiv.textContent.trim()
        };

        // 显示加载状态
        showLoading(true);

        // 使用 jQuery AJAX 发送请求
        $.ajax({
            url: '/addPost',
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(formData),
            success: function(response) {
                showLoading(false);

                if (response.success) {
                    showNotification('添加成功', true);
                    addModal.style.display = 'none';
                } else {
                    showNotification(response.message || '添加失败', false);
                }
            },
            error: function(xhr, status, error) {
                showLoading(false);
                showNotification('服务器错误: ' + xhr.status, false);
            }
        });
    });

// 表单验证函数
    function validateForm() {
        if (!nameInput.value.trim()) {
            showNotification('请输入昵称', false);
            nameInput.focus();
            return false;
        }

        if (!titleInput.value.trim()) {
            showNotification('请输入标题', false);
            titleInput.focus();
            return false;
        }

        if (titleInput.value.length > 10) {
            showNotification('标题长度不能超过10个字符', false);
            titleInput.focus();
            return false;
        }

        if (!contentDiv.textContent.trim()) {
            showNotification('请输入内容', false);
            contentDiv.focus();
            return false;
        }

        return true;
    }

// 显示通知函数
    function showNotification(message, isSuccess) {
        const notification = document.createElement('div');
        notification.className = isSuccess ? 'notification success' : 'notification error';
        notification.textContent = message;
        document.body.appendChild(notification);

        // 添加动画类
        setTimeout(() => {
            notification.classList.add('show');
        }, 10);

        // 3秒后移除通知
        setTimeout(() => {
            notification.classList.remove('show');
            setTimeout(() => {
                document.body.removeChild(notification);
            }, 300);
        }, 3000);
    }

// 显示/隐藏加载状态
    function showLoading(isLoading) {
        if (isLoading) {
            saveButton.disabled = true;
            saveButton.textContent = '保存中...';
        } else {
            saveButton.disabled = false;
            saveButton.textContent = '保存';
        }
    }
    // 为取消按钮添加点击事件监听器
});